package com.jy.modules.cims.buyback.service;

import java.math.BigDecimal;
import java.text.ParseException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;

import com.jy.modules.cims.common.CimsConstant;
import com.jy.modules.cims.common.sysUtils.DateTimeUtils;
import com.jy.modules.cims.component.common.service.TCMmCooperorgDealService;
import com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService;
import com.jy.modules.cims.component.common.service.TCMmCreditDetailService;
import com.jy.modules.cims.component.creditRight.ICCreditRight;
import com.jy.modules.cims.component.deal.ICDeal;
import com.jy.modules.cims.data.common.dto.TCMmCreditDealDetailDTO;
import com.jy.modules.cims.data.common.dto.TCMmCreditDetailDTO;
import com.jy.modules.cims.data.dao.BuyBackDao;
import com.jy.modules.cims.data.dao.DealDao;
import com.jy.modules.cims.data.dto.CreditDetailDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateDto;
import com.jy.modules.cims.data.dto.credit.CreditValueCalculateResultDto;
import com.jy.modules.cims.interact.ICInteract;
import com.jy.modules.cims.interact.IInteractAssist;
import com.jy.modules.cims.settle.service.CreditRedemptionService;

public class BuyBackCommonService {
	
	@Autowired
	protected BuyBackDao buyBackDao;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CInteractAssist")
	protected IInteractAssist iInteractAssist;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.interact.CCInteractImpl")
	protected ICInteract iCInteract;

	@Autowired
	@Qualifier("com.jy.modules.cims.settle.service.CreditRedemptionService")
	protected CreditRedemptionService creditRedemptionService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDealDetailService")
	protected TCMmCreditDealDetailService creditDealDetailService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCreditDetailService")
	protected TCMmCreditDetailService creditDetailService;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.common.service.TCMmCooperorgDealService")
	protected TCMmCooperorgDealService cooperorgDealService;
	
	@Autowired
	protected DealDao dealDao;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.creditRight.CCreditRightImpl")
	protected ICCreditRight creditRight;
	
	@Autowired
	@Qualifier("com.jy.modules.cims.component.deal.CDealImpl")
	protected ICDeal iCDeal;
	
	/**
	 * 得到贷款回购列表
	 * @param cooperorgDealDTO
	 * @return
	 * @throws Exception
	 */
	protected List<TCMmCreditDealDetailDTO> getBuyBackContractList(String batchId) throws Exception {
		Map<String, Object> creditDealSearchParams = new HashMap<String, Object>();
		String[] coreCreditStatus = new String[]{   
									CimsConstant.CORE_CREDIT_STATUS_LOANREDEEM, 
					                CimsConstant.CORE_CREDIT_STATUS_RED,
			                        CimsConstant.CORE_CREDIT_STATUS_SETTLE_CANCEL};
		String[] creditStatus = new String[] {CimsConstant.CREDIT_STATUS_WIN, CimsConstant.CREDIT_STATUS_END};
		TCMmCreditDealDetailDTO creditDealDetailDTO = new TCMmCreditDealDetailDTO();
		creditDealDetailDTO.setDealStreamCode(batchId);    //交易流水号
		creditDealSearchParams.put("dto", creditDealDetailDTO);
		creditDealSearchParams.put("creditSource", CimsConstant.CREDIT_SOURCE_LOA);   //债权来源: 02-贷款
		creditDealSearchParams.put("coreCreditStatuss", coreCreditStatus);       //核心债权状态: 01-正常, 95-提前结清 ...
		creditDealSearchParams.put("creditorStatuss", creditStatus);//债权状态: 02-已确认 04-泯灭
		List<TCMmCreditDealDetailDTO> creditDealDetailDTOList  = buyBackDao.getBuyBackContractList(creditDealSearchParams);
		return creditDealDetailDTOList;
	}
	
	

	/**
	 * 调用4028接口获取回购日债权价值
	 */
	protected List<TCMmCreditDetailDTO> getBuyBackVal(List<TCMmCreditDetailDTO> creditDetailList, String redeemDateStr) throws ParseException {
		Date redeemDate = DateTimeUtils.parseDate(redeemDateStr, "yyyy-MM-dd");
		String busiNoForInteract = iInteractAssist.getBusiNoForInteract();
		iInteractAssist.registerDealIrtService(busiNoForInteract);

		CreditValueCalculateDto creditValueCalculateDto = new CreditValueCalculateDto();
		List<CreditValueCalculateDto.CreditValueCalculateBatch> batchIdList = new ArrayList<CreditValueCalculateDto.CreditValueCalculateBatch>();
		/* 保存执行上下文 */
		for (TCMmCreditDetailDTO creditDetail : creditDetailList) {
			CreditValueCalculateDto.CreditValueCalculateBatch cc = new CreditValueCalculateDto.CreditValueCalculateBatch();
			cc.setTransferId(creditDetail.getTransferId());
			cc.setCreidtId(creditDetail.getCreditCode());
			cc.setCreditDate(redeemDate);
			cc.setEachRepaymentValue(creditDetail.getThisRepaySum());
			batchIdList.add(cc);
		}
		creditValueCalculateDto.setBatchIdList(batchIdList);
		creditValueCalculateDto.setDealCode(busiNoForInteract);
		List<CreditValueCalculateResultDto> rslist = iCInteract.getCreditValue(creditValueCalculateDto);
		if (rslist == null) {
			return null;
		}
		Map<String, CreditValueCalculateResultDto> map = new HashMap<String, CreditValueCalculateResultDto>();
		for (CreditValueCalculateResultDto creditValueCalculateResultDto : rslist) {
			map.put(creditValueCalculateResultDto.getTransferId(), creditValueCalculateResultDto);
		}
		List<TCMmCreditDetailDTO> resultlist = new ArrayList<TCMmCreditDetailDTO>();
		for (TCMmCreditDetailDTO tcMmCreditDetailDTO : creditDetailList) {
			CreditValueCalculateResultDto creditValueCalculateResultDto = map.get(tcMmCreditDetailDTO.getTransferId());
			if (null != creditValueCalculateResultDto) {
				BigDecimal redeemValue = creditValueCalculateResultDto.getCreditValue();// 贷款回购日价格
				tcMmCreditDetailDTO.setThisMakeCreditorValue(redeemValue);
				tcMmCreditDetailDTO.setRedeemDate(redeemDate);
				tcMmCreditDetailDTO.setRedemptionStatus(CimsConstant.DEAL_STATUS_CREATE);
				resultlist.add(tcMmCreditDetailDTO);
			}
		}

		return resultlist;
	}
	
	/**
	 * 得到匹配债权金额
	 * @param credit
	 * @param batchId
	 * @return
	 */
	protected BigDecimal getMatchAmt(CreditDetailDto credit,String contractCode, String repayType) {
		BigDecimal matchAmt = BigDecimal.ZERO;
		String transferId = credit.getTransferId();//转让编号
		String creditStatus = credit.getCreditorStatus();//债权状态
		Date advFinishDate = credit.getBizDate();//提前结清日期
		Date redeemDate = credit.getRedeemDate();//回购日期
		BigDecimal backContractAmt = credit.getMakeCreditorValue();//回购贷款价格
		BigDecimal backTotalAmt = credit.getBackTotalValue();//本息和
		if (CimsConstant.REPLACE_TYPE_FULL_MATCH.equals(repayType) ){
			//全匹债权
			matchAmt = backTotalAmt.subtract(backContractAmt);
		} else if (CimsConstant.REPLACE_TYPE_FULL_RETURN.equals(repayType) ) {
			//全返现
			matchAmt = BigDecimal.ZERO;
		} else {
			//本金匹债权利息返现 TODO
			Map<String, Object> paramMap = new HashMap<String, Object>();
			if (CimsConstant.CREDIT_STATUS_END.equals(creditStatus) 
					&& advFinishDate != null) {
				paramMap.put("redeemDate", advFinishDate);
			} else {
				paramMap.put("redeemDate", redeemDate);
			}
			paramMap.put("transferId", transferId);
			BigDecimal returnAmt = buyBackDao.getReturnAmt(paramMap);
			if (returnAmt == null) {
				returnAmt = BigDecimal.ZERO;
			}
			matchAmt = backTotalAmt.subtract(backContractAmt).subtract(returnAmt);
		}
				
		
		return matchAmt;
	}
	
	/**
	 * 月还处理方式
	 * @param contractCode
	 * @return
	 */
	protected String getRepayType(String contractCode) {
		Map<String, Object> paramMap = new HashMap<String, Object>();
		paramMap.put("contractCode", contractCode);
		String repayType = buyBackDao.getRepayType(paramMap);
		if (repayType == null) {
			//默认全匹债权
			throw new RuntimeException("合约["+contractCode+"]的月还处理方式不能为空，请在合约管理中配置债权结算参数");
//			repayType = CimsConstant.REPLACE_TYPE_FULL_MATCH;
		}
		return repayType;
	}
	
	/**
	 * 组装贷款回购查询条件
	 * @param contractCode
	 * @param packageNum
	 * @param date
	 * @param dtoLoan
	 * @return
	 */
	public Map<String, Object> getBuyBackParamMap(String contractCode,
			String packageNum, String redeemDate) {
		Map<String, Object> searchCreditParams = new HashMap<String, Object>();
		// 贷款债权明细查询条件
		TCMmCreditDetailDTO dtoLoan = new TCMmCreditDetailDTO();
		dtoLoan.setPackageNum(packageNum);// 债权包编号
		dtoLoan.setContractCode(contractCode);// 合约编号
		dtoLoan.setCreditSource(CimsConstant.CREDIT_SOURCE_LOA);// 债权来源"02"-来自贷款
		dtoLoan.setRedemptionStatus(CimsConstant.CREDIT_REDEMPTION_CK);// 可以选择赎回的债权
		searchCreditParams.put("redeemDate", redeemDate);//赎回日期
		searchCreditParams.put("dto", dtoLoan);
		//设置债权状态
		String[] creditorStatuss = new String[] {
				CimsConstant.CREDIT_STATUS_WIN, //已确认
				CimsConstant.CREDIT_STATUS_END  // 泯灭
		};
		//设置核心债权状态
		searchCreditParams.put("creditorStatuss", creditorStatuss);
		String[] coreStatuss = new String[]{   
				CimsConstant.CORE_CREDIT_STATUS_LOANREDEEM, 
                CimsConstant.CORE_CREDIT_STATUS_RED,
                CimsConstant.CORE_CREDIT_STATUS_SETTLE_CANCEL};
		searchCreditParams.put("coreStatuss", coreStatuss);
		return searchCreditParams;
	}
}
